package com.swz.dcrm.ui.mine;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.swz.dcrm.adpter.CustomAdapter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.adpter.ScheduleAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.ClueRecord;
import com.swz.dcrm.model.Page;
import com.swz.dcrm.model.Schedule;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import io.blackbox_vision.materialcalendarview.view.CalendarView;

import com.swz.dcrm.ui.home.ClueDetailFragmentArgs;
import com.swz.dcrm.ui.viewmodel.ScheduleViewModel;
import com.swz.dcrm.util.DateUtils;
import com.swz.dcrm.util.Tool;
import com.xh.baselibrary.callback.OnClickListener;
import com.xh.baselibrary.widget.BounceScrollView;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class ScheduleFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.calendar_view)
    CalendarView calendarView;
    @BindView(R.id.toolbar)
    ConstraintLayout toolbar;
    @BindView(R.id.scroll)
    BounceScrollView scrollView;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private String current;
    private String currentDate;
    private ScheduleAdapter scheduleAdapter;

    private int page=1;
    private int size=10;
    private int total;

    @Inject
    ScheduleViewModel scheduleViewModel;

    public static ScheduleFragment newInstance() {

        return new ScheduleFragment();
        // Required empty public constructor
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_schedule;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        current= DateUtils.dateFormat(new Date(),"yyyy M月 d日");
        currentDate=DateUtils.getCurrentDate();
        title.setText(getString(R.string.schedule_management_title));
        tvRight.setText(getString(R.string.schedule_management_add));
        rv.setLayoutManager(new LinearLayoutManager(getContext()){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });

        scrollView.setOnScrollChangeListener((BounceScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {

                if(scrollY> Tool.dip2px(getActivity(),30)){
                    title.setText(current);
                }else {
                    title.setText(getString(R.string.schedule_management_title));
                }

        });
        smartRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            if(scheduleAdapter!=null&&scheduleAdapter.getItemCount()>=total){
                smartRefreshLayout.finishLoadmore();
                smartRefreshLayout.setEnableLoadmore(false);
                return;
            }else {
                page++;
                onLoadRetry();
            }
        });
        calendarView.shouldAnimateOnEnter(true)
                .setFirstDayOfWeek(Calendar.MONDAY)
                .setOnDateClickListener(this::onDateClick)
                .setOnMonthChangeListener(this::onMonthChange)
                .setOnDateLongClickListener(this::onDateLongClick)
                .setOnMonthTitleClickListener(this::onMonthTitleClick);

        if (calendarView.isMultiSelectDayEnabled()) {
            calendarView.setOnMultipleDaySelectedListener(this::onMultipleDaySelected);
        }

        calendarView.update(Calendar.getInstance(Locale.getDefault()));

        return true;
    }

    @Override
    public void onLoadRetry() {
        if(!isNetworkConnected(getContext())){
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
        }
        smartRefreshLayout.setEnableLoadmore(true);

        scheduleViewModel.getSchedule(currentDate,DateUtils.getDateAfter(DateUtils.dateParse(currentDate,"yyyy-MM-dd"),1))
                .observe(this, pageBaseResponse -> {
                    if(pageBaseResponse==null){
                        return;
                    }
                    total=pageBaseResponse.getData().getTotal();
                   if(scheduleAdapter==null){
                       scheduleAdapter=new ScheduleAdapter(getContext(),pageBaseResponse.getData().getList());
                       scheduleAdapter.setOnClickListener(onClickListener);
                       rv.setAdapter(scheduleAdapter);
                   }else {
                       scheduleAdapter.refresh(pageBaseResponse.getData().getPageNum(),pageBaseResponse.getData().getList());
                   }
                });
    }

    private void onMonthTitleClick(Date date) {
    }

    private void onDateLongClick(Date date) {
    }
    
    private void onMonthChange(Date date) {
    }

    private void onMultipleDaySelected(int i, List<Date> dates) {
    }

    private void onDateClick(Date date) {
        currentDate=DateUtils.dateFormat(date,"yyyy-MM-dd");
        current= DateUtils.dateFormat(date,"yyyy M月 d日");
        onLoadRetry();
    }
 

    @OnClick(R.id.iv_back)
    public void backClick() {
        NavHostFragment.findNavController(this).navigateUp();
    }
    @OnClick(R.id.tv_right)
    public void right(){
        EditScheduleFragmentArgs.Builder builder=new EditScheduleFragmentArgs.Builder();
        builder.setDate(currentDate);
        go(null,R.id.action_scheduleFragment_to_editScheduleFragment,builder.build().toBundle());
    }

   OnClickListener<Schedule> onClickListener= schedule -> {

           ScheduleDetailFragmentArgs.Builder builder=new ScheduleDetailFragmentArgs.Builder();
           builder.setSchedule(new Gson().toJson(schedule));
           go(null,R.id.action_scheduleFragment_to_scheduleDetailFragment,builder.build().toBundle());

   };


}
